package com.example.flower_shop.controller;

import com.example.flower_shop.common.ApiResponse;
import com.example.flower_shop.dto.address.AddressDTO;
import com.example.flower_shop.dto.address.AddressVO;
import com.example.flower_shop.entity.Address;
import com.example.flower_shop.exception.BusinessException;
import com.example.flower_shop.service.AddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "收货地址管理")
@RestController
@RequestMapping("/api/addresses")
@RequiredArgsConstructor
@Validated
@Slf4j
public class AddressController {

    private final AddressService addressService;

    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || authentication.getPrincipal() == null) {
            log.error("用户未登录");
            throw new BusinessException("USER_NOT_AUTHENTICATED", "用户未登录");
        }
        try {
            return (Long) authentication.getPrincipal();
        } catch (Exception e) {
            log.error("无法获取用户ID: {}", e.getMessage());
            throw new BusinessException("USER_NOT_AUTHENTICATED", "无法获取用户信息");
        }
    }

    @ApiOperation("获取收货地址列表")
    @GetMapping
    public ApiResponse<List<AddressVO>> getAddresses() {
        Long userId = getCurrentUserId();
        log.info("获取收货地址列表 - 用户ID: {}", userId);
        List<AddressDTO> addresses = addressService.getAddressList(userId);
        List<AddressVO> addressVOs = addresses.stream()
                .map(dto -> new AddressVO(dto))
                .collect(Collectors.toList());
        return ApiResponse.success(addressVOs);
    }

    @ApiOperation("获取收货地址详情")
    @GetMapping("/{addressId}")
    public ApiResponse<AddressDTO> getAddress(
            @PathVariable Long addressId) {
        Long userId = getCurrentUserId();
        log.info("获取收货地址详情 - 用户ID: {}, 地址ID: {}", userId, addressId);
        return ApiResponse.success(addressService.getAddress(userId, addressId));
    }

    @ApiOperation("创建收货地址")
    @PostMapping
    public ApiResponse<AddressVO> createAddress(@Valid @RequestBody AddressDTO addressDTO) {
        Long userId = getCurrentUserId();
        log.info("创建收货地址 - 用户ID: {}, 地址信息: {}", userId, addressDTO);
        AddressDTO createdAddress = addressService.createAddress(userId, addressDTO);
        return ApiResponse.success(new AddressVO(createdAddress));
    }

    @ApiOperation("更新收货地址")
    @PutMapping("/{id}")
    public ApiResponse<AddressVO> updateAddress(
            @PathVariable Long id,
            @Valid @RequestBody AddressDTO addressDTO) {
        Long userId = getCurrentUserId();
        log.info("更新收货地址 - 用户ID: {}, 地址ID: {}, 地址信息: {}", userId, id, addressDTO);
        AddressDTO updatedAddress = addressService.updateAddress(userId, id, addressDTO);
        return ApiResponse.success(new AddressVO(updatedAddress));
    }

    @ApiOperation("删除收货地址")
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteAddress(@PathVariable Long id) {
        Long userId = getCurrentUserId();
        log.info("删除收货地址 - 用户ID: {}, 地址ID: {}", userId, id);
        addressService.deleteAddress(userId, id);
        return ApiResponse.success(null);
    }

    @ApiOperation("设置默认收货地址")
    @PostMapping("/{id}/default")
    public ApiResponse<Void> setDefaultAddress(@PathVariable Long id) {
        Long userId = getCurrentUserId();
        log.info("设置默认收货地址 - 用户ID: {}, 地址ID: {}", userId, id);
        addressService.setDefaultAddress(userId, id);
        return ApiResponse.success(null);
    }

    @ApiOperation("获取默认收货地址")
    @GetMapping("/default")
    public ApiResponse<AddressDTO> getDefaultAddress() {
        Long userId = getCurrentUserId();
        log.info("获取默认收货地址 - 用户ID: {}", userId);
        return ApiResponse.success(addressService.getDefaultAddress(userId));
    }
}